
package cn.nubia.admin.application.service;

import cn.nubia.admin.api.jinshan.bean.CheckFileList;
import cn.nubia.admin.api.jinshan.service.CheckService;
import cn.nubia.admin.application.bean.*;
import cn.nubia.admin.application.query.SoftQuery;
import cn.nubia.admin.common.constant.SystemConstant;
import cn.nubia.admin.sysconfig.bean.Category;
import cn.nubia.admin.sysconfig.bean.SystemLog;
import cn.nubia.admin.sysconfig.service.CategoryService;
import cn.nubia.admin.common.constant.TFEnum;
import cn.nubia.admin.common.mybatis.bean.Paged;
import cn.nubia.admin.common.mybatis.bean.Query;
import cn.nubia.admin.common.mybatis.service.BaseServiceImpl;
import cn.nubia.admin.common.springmvc.WebContext;
import cn.nubia.admin.common.utils.BeanUtils;
import cn.nubia.admin.common.utils.DateUtil;
import cn.nubia.admin.sysconfig.service.SystemLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by justin on 15/6/29.
 */
@Service
public class SoftService extends BaseServiceImpl<Soft> {
    @Autowired
    SoftItemService softItemService;
    @Autowired
    ScreenshotService screenshotService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    FirewareService firewareService;
    @Autowired
    SystemLogService systemLogService;
    @Autowired
    CheckService checkService;

    /**
     * 根据packageName获取软件信息。不存在则返回null
     * @param packageName
     * @return
     */
    public Soft getSoftByPackageName(String packageName) {
        Query<Soft> query = Query.build(Soft.class);
        query.addEq(Soft.COLUMN_PACKAGENAME, packageName);
        List<Soft> softs = findByQuery(query);
        if(softs.size() < 1){
            return  null;
        }else {
            return softs.get(0);
        }
    }

    /****
     * 上传APK是处理
     */
    public void processAddSoftItem(SoftVO vo) {
        Soft soft = vo.initSoftInfo();
        SoftItem softItem = vo.initSoftItem();
        Integer currTime = DateUtil.getCurrentTime();
        Integer adminId = WebContext.getCachedUser().getId();//WebContext.getCachedUser().getId()
        String  adminName = WebContext.getCachedUser().getName();//WebContext.getCachedUser().getName()
        //如果存在soft，则更新。否则新增soft
        soft.setLastModifyTime(currTime);

        if(soft.getId()!=null){
            //更新Soft
            Soft domainSoft = get(soft.getId());
            soft.copyStakeProperties(domainSoft);
            soft.setLastModifyTime(currTime);
            update(soft);
            systemLogService.log(SystemLog.ModuleTypeEnum.LISTSOFT, SystemLog.OperateTypeEnum.EDIT, soft.getId());
        }else {
            //添加Soft
            soft.setCreateAdminId(adminId);
            soft.setCreateAdminName(adminName);
            soft.setCreateTime(currTime);
            soft = insert(soft);
            systemLogService.log(SystemLog.ModuleTypeEnum.LISTSOFT, SystemLog.OperateTypeEnum.ADD,soft.getId());
        }
        softItem.setSoftId(soft.getId());
        softItem.setLastModifyTime(currTime);
        if(softItem.getId()==null){
            //新增
            softItem.setCreateTime(currTime);
            softItem.setCreateAdminId(adminId);
            softItem.setCreateAdminName(adminName);
            if(softItem.getState()==SoftItem.STATE_CHECKED){
                //直接审核通过
                softItem.setCheckAdminId(adminId);
                softItem.setCheckAdminName(adminName);
                softItem.setCheckTime(currTime);
                softItem.setPublishTime(currTime);
            }
            softItemService.insert(softItem);
            systemLogService.log(SystemLog.ModuleTypeEnum.LISTSOFTITEMS, SystemLog.OperateTypeEnum.ADD,softItem.getId());
        }else{
            SoftItem domainSoftItem = softItemService.get(softItem.getId());
            if(softItem.getState()==SoftItem.STATE_CHECKED){
                //直接审核通过
                softItem.setCheckAdminId(adminId);
                softItem.setCheckAdminName(adminName);
                softItem.setCheckTime(currTime);
                softItem.setPublishTime(currTime);
            }
            softItem.copyStakeProperties(domainSoftItem);
            //更新
            softItemService.update(softItem);
            systemLogService.log(SystemLog.ModuleTypeEnum.LISTSOFTITEMS, SystemLog.OperateTypeEnum.EDIT, softItem.getId());
        }
        if(softItem.getState()==SoftItem.STATE_CHECKED){
            systemLogService.log(SystemLog.ModuleTypeEnum.LISTSOFTITEMS, SystemLog.OperateTypeEnum.CHECK, softItem.getId());
        }
        Integer softItemId = softItem.getId();
        //更新截图信息
        if(vo.getScreenshotUrl()!=null&&vo.getScreenshotUrl().size()>0){
            for(int i=1;i<vo.getScreenshotUrl().size();i++){
                ScreenShot screenShot = screenshotService.get(vo.getScreenshotId().get(i));
                if(screenShot!=null){
                    screenShot.setSortIndex(i);
                    screenShot.setSoftItemId(softItemId);
                    screenShot.setIsDelete(TFEnum.FALSE.getValue());
                    Integer curr = DateUtil.getCurrentTime();
                    screenShot.setCreateTime(curr);
                    screenshotService.update(screenShot);
                }
            }
        }
        softItemService.checkForTheLastVersion(soft, softItem);
        CheckFileList checkFileList = new CheckFileList();
        checkFileList.addScanFile(SystemConstant.staticHost+softItem.getFileUrl(),softItem.getFileMD5(),"0");
        checkService.check(checkFileList);
    }


    public boolean saveSoft(Soft soft){
        if(soft.getId()==null){

        }else{
            //
        }
        return true;
    }


    public SoftVO getSoftBySoftItemId(Integer softItemId) {
        SoftVO vo = new SoftVO();
        SoftItem softItem = softItemService.get(softItemId);
        if(softItem!=null){
            BeanUtils.copyProperties(softItem, vo);
            vo.setSoftItemId(softItem.getId());
            vo.setSubmitType(softItem.getState());

            Soft soft = get(softItem.getSoftId());
            BeanUtils.copyProperties(soft, vo);
            vo.setSoftId(soft.getId());
            if(softItem.getResolution()!=null&&softItem.getResolution()>0){
                vo.setResolutionShow(getResolutionShow(softItem.getResolution()));
            }
            if(soft.getCategoryId()!=null){
                vo.initCategory(categoryService.constructorCategory(soft.getCategoryId()));
            }
            List<ScreenShot> screenShots = screenshotService.findBySoftItemId(softItem.getId());
            vo.setScreenShots(screenShots);
        }
        //max min处理
        vo.setMaxFirewareName(firewareService.getFirewareNameByFirewareSDK(vo.getMaxFirewareId()));
        vo.setMinFirewareName(firewareService.getFirewareNameByFirewareSDK(vo.getMinFirewareId()));
        return vo;
    }

    public SoftVO getSoftId(Integer id) {
        SoftVO vo = new SoftVO();
        Soft soft = get(id);
        BeanUtils.copyProperties(soft, vo);
        vo.setSoftId(soft.getId());
        if(soft.getCategoryId()!=null){
            vo.initCategory(categoryService.constructorCategory(soft.getCategoryId()));
        }
        return vo;
    }

    public Paged<Soft> findList(SoftQuery softQuery) {
        String sql = "select a.soft_id as id, " +
                " a.soft_name as soft_name, " +
                " a.package_name as package_name, " +
                " a.download_number as download_number, " +
                " a.developer_name as developer_name, " +
                " a.create_time as create_time, " +
                " a.category_id as category_id " +
                " from nb_soft a  where  a.is_delete=0 and a.last_soft_item_id>0 ";
        String condition = "";
        if(softQuery.getId()!=null && softQuery.getId() > 0){
            condition += " AND  a.soft_id = "+softQuery.getId();
        }
        if(softQuery.getSoftName()!=null && softQuery.getSoftName() != ""){
            condition += " AND  a.soft_name like '%"+softQuery.getSoftName()+"%' ";
        }
        if(softQuery.getPackageName()!=null && softQuery.getPackageName() != ""){
            condition += " AND  a.package_name like '%"+softQuery.getPackageName()+"%' ";
        }
        if(softQuery.getSeo()!=null && softQuery.getSeo() != ""){
            condition += " AND  a.seo like '%"+softQuery.getSeo()+"%' ";
        }

        if(softQuery.getDeveloperName()!=null && softQuery.getDeveloperName() != ""){
            condition += " AND  a.developer_name like '%"+softQuery.getDeveloperName()+"%' ";
        }

        if (softQuery.getCategoryId3() != null && softQuery.getCategoryId3() > 0) {
            condition += " AND  a.category_id = " + softQuery.getCategoryId3();
        } else if (softQuery.getCategoryId2() != null && softQuery.getCategoryId2() > 0) {
            condition += " AND  a.category_parent_id = " + softQuery.getCategoryId2();
        }else if (softQuery.getCategoryId() != null && softQuery.getCategoryId() > 0) {
            String secCategories ="";
            List<Category> categories=categoryService.getSubCategoryList(softQuery.getCategoryId());
            for(int i=0;i<categories.size();i++){
                secCategories+=categories.get(i).getId();
                if(i!=categories.size()-1)secCategories+=",";
            }
            System.out.println(secCategories);
            condition += " AND  a.category_parent_id in (" + secCategories+") ";
        }

        if(softQuery.getIsAccredit()!=null && softQuery.getIsAccredit() != -99){
            condition += " AND  a.is_accredit = "+softQuery.getIsAccredit();
        }

        if(softQuery.getCreateTimes()!=null){
            condition += " AND  a.create_time >= "+ DateUtil.getIntegerTime(softQuery.getCreateTimes())+" ";
        }

        if(softQuery.getCreateTimee()!=null){
            condition += " AND  a.create_time <= "+ DateUtil.getIntegerTime(softQuery.getCreateTimee())+" ";
        }
        sql +=  condition;

        String order = "";
        order += " order by a.create_time desc ";
        sql += order;
//        System.out.println(sql);
        Paged<Soft> items = findPageBySql(sql, Soft.class,softQuery.getPageNo(),softQuery.getPageSize());
        setCategoryName(items);
        return items;
    }

    private void setCategoryName(Paged<Soft> softPaged){
        if(softPaged.getListData()!=null){
            for(Soft soft : softPaged.getListData()){
                soft.initCategoryName(categoryService.getCategoryConstruct(soft.getCategoryId()));
            }
        }

    }

    public String getResolutionShow(Integer ret){
        String value = "";
        String sql = "SELECT id, width, height, size, value, platform_id FROM nb_resolution_map where is_delete=0 AND "+ret+"&value=value";
        List<ResolutionMap> resolutions = findBySql(sql,ResolutionMap.class);
        for(ResolutionMap resolution : resolutions){
            value += resolution.getWidth()+"X"+resolution.getHeight()+"  ";
        }
        return value;
    }

    /***
     * 根据软件ID删除软件
     * @param softId
     * @return
     */
    public boolean delSoft(Integer softId) {
        softItemService.delSoftItemBySoftId(softId);
        Soft soft = get(softId);
        soft.setIsDelete(Soft.STATE_DELETE);
        Integer curr = DateUtil.getCurrentTime();
        soft.setLastModifyTime(curr);
        update(soft);
        systemLogService.log(SystemLog.ModuleTypeEnum.LISTSOFT, SystemLog.OperateTypeEnum.DEL, soft.getId());
        return true;
    }

    public List<Soft> findSoftList(SoftQuery softQuery) {
        Query<Soft> query = Query.build(Soft.class);
        if(softQuery.getId()!=null && softQuery.getId() > 0){
            query.addEq(Soft.COLUMN_ID,softQuery.getId());
        }
        if(softQuery.getSoftName()!=null && softQuery.getSoftName() != ""){
            query.addLike(Soft.COLUMN_SOFTNAME,softQuery.getSoftName());
        }
        query.addNotEq(Soft.COLUMN_ISDELETE, Soft.STATE_DELETE);
        query.addOrder(Soft.COLUMN_LASTPUBLISHTIME, Query.DBOrder.DESC);
        query.setPaged(1, softQuery.getPageSize());
        Paged<Soft> softPaged = findPagedByQuery(query);
        return softPaged.getListData();
    }

}
